package com.llh.demo4shiro.service;

import com.llh.demo4shiro.model.Role;
import com.llh.demo4shiro.model.User;
import com.llh.demo4shiro.model.relation.UserRole;
import com.llh.demo4shiro.repository.RoleRepo;
import com.llh.demo4shiro.repository.UserRepo;
import com.llh.demo4shiro.repository.relation.UserRoleRepo;
import com.llh.demo4shiro.utils.PasswordUtil;
import com.llh.demo4shiro.vo.UserRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>CreatedAt: 2020/9/16 16:17</p>
 *
 * @author llh
 */
@Service
public class UserService {
    @Autowired
    private UserRepo userRepo;
    @Autowired
    private RoleRepo roleRepo;
    @Autowired
    private UserRoleRepo userRoleRepo;

    public User register(User user) {
        user.setPassword(PasswordUtil.hash(user.getPassword()));
        userRepo.save(user);
        return user;
    }

    public boolean existedUsername(String username) {
        User user = new User();
        user.setUsername(username);
        Example<User> example = Example.of(user);
        long count = userRepo.count(example);
        return count > 0;
    }

    public List<User> all() {
        return userRepo.findAll();
    }

    public int addRoles(UserRoles relation) {
        UserRole userRole = new UserRole()
                .setUserId(relation.getUserId());
        userRoleRepo.deleteAll(
                userRoleRepo.findAll(
                        Example.of(userRole)));
        List<UserRole> list = new ArrayList<>();
        for (Integer roleId : relation.getRoleIds()) {
            list.add(new UserRole()
                    .setRoleId(roleId)
                    .setUserId(relation.getUserId()));
        }
        userRoleRepo.saveAll(list);
        return list.size();

    }

    public List<Role> getRoles(Integer id) {
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        List<Integer> collect = userRoleRepo.findAll(Example.of(userRole))
                .stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        if (collect.isEmpty()) return Collections.emptyList();
        return roleRepo.findAllById(collect);
    }

    public Optional<User> findByUsername(String username) {
        User user = new User();
        user.setUsername(username);
        return userRepo.findOne(Example.of(user));
    }
}
